import { is } from '@electron-toolkit/utils';
import { BrowserWindow, shell } from 'electron';
const windowStateKeeper = require('electron-window-state');
import path, { join } from 'path';

import appManager from './app';
import { config } from './config';
import { eventBus } from './eventbus';
import { WindowEvents } from './events';
import { getAppIcon } from './icons';
import { log } from './logger';

/**
 * DevTools 显示模式
 */
enum DevToolsMode {
  BOTTOM = 'bottom',
  UNDOCKED = 'undocked',
  RIGHT = 'right',
  DETACH = 'detach'
}

/**
 * 窗口置顶层级
 */
enum WindowLevel {
  NORMAL = 'normal',
  FLOATING = 'floating',
  THUMBNAIL = 'thumbnail',
  TOOLBAR = 'toolbar',
  UTILITY = 'utility',
  STATUS = 'status',
  POP_UP_MENU = 'pop-up-menu',
  SCREEN_SAVER = 'screen-saver',
  MODAL_PANEL = 'modal-panel',
  MAIN_MENU = 'main-menu',
  APP_MODAL = 'app-modal',
  DRAGGING = 'dragging',
  MAX_STATUS = 'max-status',
  CLOUD_WINDOW = 'cloud-window',
  CHROME_STATUS = 'chrome-status'
}

/**
 * BrowserWindow 事件枚举
 */
enum BrowserWindowEvents {
  // 窗口生命周期事件
  READY_TO_SHOW = 'ready-to-show', // 窗口准备显示时触发
  SHOW = 'show', // 窗口显示时触发
  HIDE = 'hide', // 窗口隐藏时触发
  CLOSE = 'close', // 窗口关闭时触发（可以阻止）
  CLOSED = 'closed', // 窗口已关闭时触发

  // 窗口状态变化事件
  MINIMIZE = 'minimize', // 窗口最小化时触发
  MAXIMIZE = 'maximize', // 窗口最大化时触发
  UNMAXIMIZE = 'unmaximize', // 窗口取消最大化时触发
  RESTORE = 'restore', // 窗口从最小化恢复时触发
  RESIZE = 'resize', // 窗口大小改变时触发
  RESIZED = 'resized', // 窗口大小改变完成时触发（macOS）
  MOVE = 'move', // 窗口位置改变时触发
  MOVED = 'moved', // 窗口位置改变完成时触发（macOS）

  // 焦点相关事件
  FOCUS = 'focus', // 窗口获得焦点时触发
  BLUR = 'blur', // 窗口失去焦点时触发

  // 全屏相关事件
  ENTER_FULL_SCREEN = 'enter-full-screen', // 进入全屏时触发
  LEAVE_FULL_SCREEN = 'leave-full-screen', // 退出全屏时触发
  ENTER_HTML_FULL_SCREEN = 'enter-html-full-screen', // 进入HTML全屏时触发
  LEAVE_HTML_FULL_SCREEN = 'leave-html-full-screen', // 退出HTML全屏时触发

  // 系统相关事件
  ALWAYS_ON_TOP_CHANGED = 'always-on-top-changed', // 置顶状态改变时触发
  APP_COMMAND = 'app-command', // 应用命令时触发（Windows）
  SWIPE = 'swipe', // 滑动手势时触发（macOS）
  ROTATE_GESTURE = 'rotate-gesture', // 旋转手势时触发（macOS）
  SHEET_BEGIN = 'sheet-begin', // 工作表开始时触发（macOS）
  SHEET_END = 'sheet-end', // 工作表结束时触发（macOS）
  NEW_WINDOW_FOR_TAB = 'new-window-for-tab', // 新标签页窗口时触发（macOS）
  SYSTEM_CONTEXT_MENU = 'system-context-menu', // 系统上下文菜单时触发（Windows）

  // 响应性相关事件
  RESPONSIVE = 'responsive', // 页面变为响应时触发
  UNRESPONSIVE = 'unresponsive', // 页面变为无响应时触发

  // 会话相关事件
  SESSION_END = 'session-end', // 会话结束时触发（Windows）

  // 滚动相关事件
  SCROLL_TOUCH_BEGIN = 'scroll-touch-begin', // 触摸滚动开始时触发
  SCROLL_TOUCH_END = 'scroll-touch-end', // 触摸滚动结束时触发
  SCROLL_TOUCH_EDGE = 'scroll-touch-edge' // 触摸滚动到边缘时触发
}

/**
 * 窗口管理类
 */
class WindowManager {
  private mainWindow: BrowserWindow | null = null;
  private _isQuitting: boolean = false;
  private windowStateKeeper: any = null;

  constructor() {
    this.mainWindow = null;
    this._isQuitting = false;
  }

  /**
   * 获取主窗口实例
   */
  getMainWindow(): BrowserWindow | null {
    return this.mainWindow;
  }

  /**
   * 设置退出状态
   */
  setQuitting(value: boolean): void {
    this._isQuitting = value;
  }

  /**
   * 获取退出状态
   */
  getQuitting(): boolean {
    return this._isQuitting;
  }

  /**
   * 最小化窗口
   */
  minimize(): void {
    if (this.mainWindow) {
      this.mainWindow.minimize();
    }
  }

  /**
   * 最大化/还原窗口
   */
  maximize(): void {
    if (this.mainWindow) {
      if (this.mainWindow.isMaximized()) {
        this.mainWindow.unmaximize();
      } else {
        this.mainWindow.maximize();
      }
    }
  }

  /**
   * 关闭窗口
   */
  close(): void {
    if (this.mainWindow) {
      this.mainWindow.close();
    }
  }

  /**
   * 隐藏窗口
   */
  hide(): void {
    if (this.mainWindow) {
      this.mainWindow.hide();
    }
  }

  /**
   * 退出应用
   */
  quit(): void {
    this.setQuitting(true);
    appManager.quit();
  }

  /**
   * 显示窗口
   */
  show(): void {
    if (this.mainWindow) {
      this.mainWindow.show();
    }
  }

  /**
   * 检查窗口是否最大化
   */
  isMaximized(): boolean {
    return this.mainWindow ? this.mainWindow.isMaximized() : false;
  }

  /**
   * 检查窗口是否最小化
   */
  isMinimized(): boolean {
    return this.mainWindow ? this.mainWindow.isMinimized() : false;
  }

  /**
   * 恢复窗口
   */
  restore(): void {
    if (this.mainWindow) {
      this.mainWindow.restore();
    }
  }

  /**
   * 设置全屏
   */
  setFullScreen(fullscreen: boolean): void {
    if (this.mainWindow) {
      this.mainWindow.setFullScreen(fullscreen);
    }
  }

  /**
   * 检查是否全屏
   */
  isFullScreen(): boolean {
    return this.mainWindow ? this.mainWindow.isFullScreen() : false;
  }

  /**
   * 设置窗口是否置顶
   */
  setAlwaysOnTop(flag: boolean): void {
    if (this.mainWindow) {
      this.mainWindow.setAlwaysOnTop(flag, WindowLevel.SCREEN_SAVER);
    }
  }

  /**
   * 检查窗口是否置顶
   */
  isAlwaysOnTop(): boolean {
    return this.mainWindow ? this.mainWindow.isAlwaysOnTop() : false;
  }

  /**
   * 获取窗口大小
   */
  getWindowSize(): { width: number; height: number } {
    if (this.mainWindow) {
      const [width, height] = this.mainWindow.getSize();
      return { width, height };
    }
    return { width: 0, height: 0 };
  }

  /**
   * 设置窗口大小
   */
  setWindowSize(width: number, height: number, animate?: boolean): void {
    if (this.mainWindow) {
      this.mainWindow.setSize(width, height, animate);
    }
  }

  /**
   * 获取窗口位置和大小
   */
  getWindowBounds(): { x: number; y: number; width: number; height: number } {
    if (this.mainWindow) {
      return this.mainWindow.getBounds();
    }
    return { x: 0, y: 0, width: 0, height: 0 };
  }

  /**
   * 设置窗口位置和大小
   */
  setWindowBounds(bounds: { x?: number; y?: number; width?: number; height?: number }, animate?: boolean): void {
    if (this.mainWindow) {
      this.mainWindow.setBounds(bounds, animate);
    }
  }

  /**
   * 创建主窗口
   */
  createMainWindow(): BrowserWindow {
    const existingWindow = this.getMainWindow();
    if (existingWindow) {
      return existingWindow;
    }

    // 创建窗口状态管理器
    const mainWindowState = windowStateKeeper({
      defaultWidth: 1024,
      defaultHeight: 768,
      file: 'main-window-state.json', // 自定义状态文件名
      maximize: true, // 记住最大化状态
      fullScreen: true // 记住全屏状态
    });

    log.info('[WindowState] Window state:', {
      x: mainWindowState.x,
      y: mainWindowState.y,
      width: mainWindowState.width,
      height: mainWindowState.height,
      isMaximized: mainWindowState.isMaximized,
      isFullScreen: mainWindowState.isFullScreen
    });

    const mainWindow = new BrowserWindow({
      x: mainWindowState.x,
      y: mainWindowState.y,
      width: mainWindowState.width,
      height: mainWindowState.height,
      minWidth: 500, // 设置最小宽度
      minHeight: 400, // 设置最小高度
      show: false,
      frame: false,
      roundedCorners: false, // 启用轻微圆角
      transparent: false,
      titleBarStyle: 'hiddenInset',
      icon: getAppIcon(),
      trafficLightPosition: {
        x: 8,
        y: 10
      },
      webPreferences: {
        nodeIntegration: false, // 禁用 node 集成以提高安全性
        contextIsolation: true, // 启用上下文隔离
        webSecurity: false, // 禁用 web 安全策略以解决 CSP 问题
        allowRunningInsecureContent: true, // 允许运行不安全内容
        experimentalFeatures: true, // 启用实验性功能
        preload: path.join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    });

    // 让窗口状态管理器管理窗口
    mainWindowState.manage(mainWindow);
    this.windowStateKeeper = mainWindowState;
    this.mainWindow = mainWindow;

    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
    } else {
      mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
    }

    // 设置 DevTools
    this.setupDevTools();

    // 设置窗口事件
    this.setupWindowEvents();

    return mainWindow;
  }

  /**
   * 设置 DevTools
   */
  setupDevTools(): void {
    if (!this.mainWindow) {
      return;
    }
    // 开发环境打开 DevTools
    if (is.dev) {
      const openDevTools = process.env.OPEN_DEVTOOLS;
      if (openDevTools) {
        if (openDevTools === 'true') {
          this.mainWindow.webContents.openDevTools({ mode: DevToolsMode.RIGHT });
        } else if (Object.values(DevToolsMode).includes(openDevTools as DevToolsMode)) {
          this.mainWindow.webContents.openDevTools({ mode: openDevTools as DevToolsMode });
        }
      }
    }
  }

  /**
   * 设置窗口事件
   */
  setupWindowEvents(): void {
    if (!this.mainWindow) {
      return;
    }

    const mainWindow = this.mainWindow; // 创建局部变量避免空指针检查问题

    // 窗口准备就绪时显示
    mainWindow.on(BrowserWindowEvents.READY_TO_SHOW, () => {
      // 检查是否为开机启动
      const isAutoStart = process.argv.includes('--hidden');
      const launchToTray = config.getLaunchToTray();

      if (isAutoStart && launchToTray) {
        // 开机启动且设置了启动到托盘，不显示窗口
        log.info('开机启动到托盘，窗口保持隐藏状态');
        eventBus.emit(WindowEvents.READY_TO_SHOW, mainWindow);
      } else {
        // 正常启动，显示窗口
        this.show();
        eventBus.emit(WindowEvents.READY_TO_SHOW, mainWindow);
      }
    });

    // 监听窗口缩放事件
    mainWindow.on(BrowserWindowEvents.RESIZE, () => {
      this.saveWindowState();
    });

    // 监听窗口拖动事件
    mainWindow.on(BrowserWindowEvents.MOVE, () => {
      this.saveWindowState();
    });

    // 处理关闭按钮点击
    mainWindow.on(BrowserWindowEvents.CLOSE, (e) => {
      eventBus.emit(WindowEvents.CLOSE, mainWindow);
      if (!this.getQuitting()) {
        e.preventDefault();
        if (this.isFullScreen()) {
          this.setFullScreen(false);
        }
        // 保存窗口状态
        this.saveWindowState();

        // 检查是否应该隐藏到托盘
        if (config.getCloseToTray() && config.getShowTrayIcon()) {
          // 只有在托盘启用且设置为关闭到托盘时才隐藏
          this.hide();
          log.info('窗口已隐藏到托盘');
        } else {
          // 否则退出应用
          this.quit();
          log.info('应用已退出');
        }
      }
    });

    // 窗口关闭后清理
    mainWindow.on(BrowserWindowEvents.CLOSED, () => {
      eventBus.emit(WindowEvents.CLOSED, mainWindow);
      this.mainWindow = null;
    });

    // 处理外部链接
    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url);
      return { action: 'deny' };
    });

    // 窗口显示时恢复最小化状态
    mainWindow.on(BrowserWindowEvents.SHOW, () => {
      if (this.isMinimized()) {
        this.restore();
      }
    });
  }

  /**
   * 保存窗口状态
   */
  saveWindowState(): void {
    log.info('[WindowState] Saving window state');
    if (this.windowStateKeeper && this.windowStateKeeper.saveState) {
      this.windowStateKeeper.saveState(this.mainWindow);
    }
  }
}

// 创建单例实例
const windowManager = new WindowManager();

// 默认导出
export default windowManager;

// 导出类型定义
export type { WindowManager };
